package com.example.neartweet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;

import com.example.neartweet.ComService.LB;

public class ComposeActivity extends Activity {
	
	private CheckBox reply;
	private EditText user;
	private Button sendButton;
	private Button cancelButton;
	private EditText tweet;
	private ImageButton attachButton;
    private TextView label;
	private String message;
	private static final int SELECT_PICTURE = 1;
	private static final int TAKE_PICTURE = 2;
    private String selectedImagePath;
    private String toUser;
    protected boolean _taken;
    protected String _path;
    protected ImageView _image;
    
	private String text;
	
	private ServiceConnection mConnection;
	ComService serv;
	boolean isBound = false;
	private boolean location;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_compose);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setTitle("Compose");
		reply = (CheckBox) findViewById(R.id.reply);
		user = (EditText) findViewById(R.id.toUser);
        sendButton = (Button) findViewById(R.id.SendButton);
        cancelButton = (Button) findViewById(R.id.Cancel);
        attachButton = (ImageButton) findViewById(R.id.attachImage);
        tweet = (EditText) findViewById(R.id.tweet);
        label = (TextView) findViewById(R.id.attachLabel);
        _path = Environment.getExternalStorageDirectory() + "/images/media/make_machine_example.png";
        
        SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		int state = sharedPrefs.getInt("gps", 0);
		if (state == 0){
			location = false;
		} else {
			location = true;
		}
        
        mConnection = new ServiceConnection() {
			public void onServiceConnected(ComponentName className,
					IBinder service) {
				LB binder = (LB) service;
				serv = binder.getService();
				isBound = true;
			}
			public void onServiceDisconnected(ComponentName className) {
				isBound = false;
		    }
		};
		
		Intent intent = new Intent(this, ComService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);        
        
        sendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	SharedPreferences sharedPrefs = getSharedPreferences(
        		        getString(R.string.preference_file_key),MODE_PRIVATE);
        		String uN = sharedPrefs.getString("usr", "");
        		/*SharedPreferences.Editor editor = sharedPrefs.edit();*/
            	if(reply.isChecked()){
            		message = "To:" + user.getText().toString() + ":" + uN + ":" + tweet.getText().toString();
            		serv.receiveMessages(message);
            		serv.envia(message);
            		/*editor.putString("tweet", tweet.getText().toString());
            		editor.putString("TO", user.getText().toString());*/
            	}
            	else{
            		message = uN + ":" + tweet.getText().toString();
            		serv.receiveMessages(message);
            		serv.envia(message);
            		/*editor.putString("tweet", tweet.getText().toString());*/
            	}
            	/*editor.putInt("state", 2);
            	editor.commit();*/
            	tweet.setText("");
            	//new ComposeTask().execute(selectedImagePath);
                ComposeActivity.this.finish();
            }
        });
        
        reply.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				user.setEnabled(isChecked);
			}
		});
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
        	toUser = extras.getString("username", "");
        	if (toUser != "") {
        		reply.setChecked(true);
        		user.setText(toUser);
        	}
        }
        
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	ComposeActivity.this.finish();
            }
        });
        
        attachButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	CharSequence[] array = {"Camera", "Gallery", "URL"};
            	AlertDialog.Builder builder = new AlertDialog.Builder(ComposeActivity.this);
            	builder.setTitle(R.string.comp_attach_method);
            	builder.setItems(array, new DialogInterface.OnClickListener() {
            		public void onClick(DialogInterface dialog, int which) {
            			switch (which) {
						case 0:
							
							startCameraActivity();
							
							break;
						case 1:
							Intent intentGet = new Intent();
			                intentGet.setType("image/*");
			                intentGet.setAction(Intent.ACTION_GET_CONTENT);
			                startActivityForResult(Intent.createChooser(intentGet,
			                        "Select Picture"), SELECT_PICTURE);
			                break;
						case 2:
							//onDownload();
							break;
						default:
							break;
						}
            		}
            	});
            	builder.create().show();
            }
        });
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                String[] path = selectedImagePath.split("/");
                label.setText(path[path.length - 1]);
                label.setVisibility(View.VISIBLE);
                BitmapFactory.Options options = new BitmapFactory.Options();
        	    options.inSampleSize = 4;
        	    Bitmap bitmap = BitmapFactory.decodeFile( selectedImagePath, options );
        	    //TODO send bitmap
            } else if(requestCode == TAKE_PICTURE) {
            	onPhotoTaken(data);
            }
            
        }
    }
	
	public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(this, uri, projection, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	
	/*private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}*/
	
	protected void startCameraActivity() {
		File file = new File( "/sdcard/tmp");
		Uri outputFileUri = Uri.fromFile( file );

		Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
		intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

		startActivityForResult( intent, TAKE_PICTURE );
	}
	
	
	protected void onPhotoTaken(Intent data) {
	    _taken = true;
	    
	    File f1 = new File("/sdcard/tmp");
	    
	    Uri selectedImageUri = null;
		try {
			selectedImageUri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), f1.getAbsolutePath(), null , null));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        selectedImagePath = getPath(selectedImageUri);
        String[] path = selectedImagePath.split("/");
        label.setText(path[path.length - 1]);
        label.setVisibility(View.VISIBLE);
        ContentResolver cr = ComposeActivity.this.getContentResolver();
        try {
			InputStream is = cr.openInputStream(selectedImageUri);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*protected void onDownload() {
		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		if(clipboard.hasPrimaryClip())
			text = clipboard.getPrimaryClip().toString();
		else {
			text = "http://1.bp.blogspot.com/-kkFsF03oxOo/UPNVOdEtZBI/AAAAAAAABO8/0_I4inBy71I/s1600/tumblr_mbuypt8R0M1ri87b4o1_1280.jpg";
		}
		URL url = null;
		try {
			url = new URL (text);
		} catch (MalformedURLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		InputStream input = null;
		try {
			input = url.openStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
		    //The sdcard directory e.g. '/sdcard' can be used directly, or 
		    //more safely abstracted with getExternalStorageDirectory()
		    File storagePath = Environment.getExternalStorageDirectory();
		    OutputStream output = new FileOutputStream (new File(storagePath,"myImage.jpg"));
		    try {
		        byte[] buffer = new byte[2000000];
		        int bytesRead = 0;
		        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
		            output.write(buffer, 0, bytesRead);
		        }
		    } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
		        try {
					output.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
		    try {
				input.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}*/
	
	public static boolean copyFile(InputStream in, OutputStream out){
		byte buff[] = new byte[1024];
		int len;
		try {
			while((len = in.read(buff)) != -1) {
				out.write(buff, 0, len);
			}
			out.close();
			in.close();
		} catch(IOException e){
			return false;
		}
		return true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.compose, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		switch (item.getItemId()) {
		case R.id.action_settings:
			intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		case R.id.gps:
			if(location) {
				item.setIcon(R.drawable.gps_off);
				location = false;
				
				editor.putInt("gps", 0);
				editor.commit();
			} else {
				item.setIcon(R.drawable.gps_on);
				location = true;
				
				editor.putInt("gps", 1);
				editor.commit();
			}
			break;
		case R.id.poll:
			intent = new Intent(this, PollActivity.class);
			startActivity(intent);
			ComposeActivity.this.finish();
			break;
		case android.R.id.home:
			ComposeActivity.this.finish();
			break;
		default:
			
		}
		return super.onOptionsItemSelected(item);
	}

}
